package cn.snapvideo.flutter_aliyun_vod_upload;

import android.app.Activity;

import androidx.annotation.NonNull;


import com.alibaba.sdk.android.oss.common.OSSLog;
import com.alibaba.sdk.android.vod.upload.VODUploadCallback;
import com.alibaba.sdk.android.vod.upload.VODUploadClient;
import com.alibaba.sdk.android.vod.upload.VODUploadClientImpl;
import com.alibaba.sdk.android.vod.upload.model.UploadFileInfo;
import com.alibaba.sdk.android.vod.upload.model.VodInfo;

import java.util.HashMap;
import java.util.Map;

import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugin.common.PluginRegistry.Registrar;

/**
 * FlutterAliyunVodUploadPlugin
 */
public class FlutterAliyunVodUploadPlugin implements FlutterPlugin, MethodCallHandler {


    Registrar registrar;
    MethodChannel channel;

    VODUploadClient uploader;


    private static final String CHANNEL = "flutter_aliyun_vod_upload";


    @Override
    public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
        channel = new MethodChannel(flutterPluginBinding.getFlutterEngine().getDartExecutor(), CHANNEL);
        channel.setMethodCallHandler(this);
    }

    /**
     * Plugin registration.
     */
    public static void registerWith(Registrar registrar) {
        final MethodChannel channel = new MethodChannel(registrar.messenger(), CHANNEL);
        FlutterAliyunVodUploadPlugin flutterAliyunVodUploadPlugin = new FlutterAliyunVodUploadPlugin();
        flutterAliyunVodUploadPlugin.registrar = registrar;
        channel.setMethodCallHandler(flutterAliyunVodUploadPlugin);
    }


    @Override
    public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
        switch (call.method) {
            case "getPlatformVersion":
                result.success("Androidss " + android.os.Build.VERSION.RELEASE);
                break;
            case "init":
                init();
                break;
            case "setUploadAuthAndAddress":
                setUploadAuthAndAddress(call);
                break;
            case "resumeWithAuth":
                resumeWithAuth(call);
                break;
            case "addFile":
              addFile(call);
                break;

            case "start":
                uploader.start();
                break;
            case "pause":
                uploader.pause();
                break;
            case "stop":
                uploader.stop();
                break;
            case "resume":
                uploader.resume();
                break;
            case "clearFiles":
                uploader.clearFiles();
                break;
            default:
                result.notImplemented();
                break;
        }
    }

   void addFile(MethodCall call) {
     final String filePath = call.argument("filePath");
     final Map vodInfo = call.argument("vodInfo");
     uploader.addFile(filePath,toNewVodInfo(vodInfo));
  }

  void init() {
        uploader = new VODUploadClientImpl(registrar.context());
        VODUploadCallback callback = new VODUploadCallback() {
            public void onUploadStarted(UploadFileInfo uploadFileInfo) {
                OSSLog.logError("onUploadStarted ------------- ");

                //通知手机端该文件开始上传了
                channel.invokeMethod("onUploadStarted", toMap(uploadFileInfo));

                OSSLog.logError("file path:" + uploadFileInfo.getFilePath() +
                        ", endpoint: " + uploadFileInfo.getEndpoint() +
                        ", bucket:" + uploadFileInfo.getBucket() +
                        ", object:" + uploadFileInfo.getObject() +
                        ", status:" + uploadFileInfo.getStatus());
            }

            public void onUploadSucceed(UploadFileInfo info) {
                OSSLog.logDebug("onsucceed ------------------" + info.getFilePath());
                //通知手机端该文件开始上传了
                channel.invokeMethod("onUploadSucceed", toMap(info));
            }

            public void onUploadProgress(UploadFileInfo info, long uploadedSize, long totalSize) {
                OSSLog.logDebug("onProgress ------------------ " + info.getFilePath() + " " + uploadedSize + " " + totalSize);
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("uploadedSize", uploadedSize);
                map.put("totalSize", totalSize);


                channel.invokeMethod("onUploadProgress", toMap(info));
            }

        };
        uploader.init(callback);
    }


    //刷新上传凭证
    void resumeWithAuth(MethodCall call) {
        final String uploadAuth = call.argument("uploadAuth");
        uploader.resumeWithAuth(uploadAuth);
    }

    //设置上传凭证和地址
    void setUploadAuthAndAddress(MethodCall call) {
        final Map uploadFileInfo = call.argument("uploadFileInfo");
        final String uploadAuth = call.argument("uploadAuth");
        final String uploadAddress = call.argument("uploadAddress");
        uploader.setUploadAuthAndAddress(toUploadFileInfo(uploadFileInfo), uploadAuth, uploadAddress);
    }


    @Override
    public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
        channel.setMethodCallHandler(null);
    }


    Map<String, Object> toMap(UploadFileInfo uploadFileInfo) {
        Map<String, Object> m1 = new HashMap<String, Object>();
        m1.put("filePath", uploadFileInfo.getFilePath());
        m1.put("status", uploadFileInfo.getStatus().toString());
        Map<String, Object> m2 = new HashMap<String, Object>();
        VodInfo vodInfo = uploadFileInfo.getVodInfo();
        m2.put("coverUrl", vodInfo.getCoverUrl());
        m2.put("fileName", vodInfo.getFileName());
        m2.put("fileSize", vodInfo.getFileSize());

        m1.put("vodInfo", vodInfo);
        return m1;
    }


    VodInfo toNewVodInfo(Map<String, Object> m2){
      VodInfo vodInfo = new VodInfo();
      vodInfo.setTitle(String.valueOf(m2.get("title")));
      vodInfo.setDesc(String.valueOf(m2.get("desc")));
      return vodInfo;
    }

    UploadFileInfo toUploadFileInfo(Map<String, Object> m1) {
        String filePath = String.valueOf(m1.get("filePath"));
        String status = String.valueOf(m1.get("status"));
        for (UploadFileInfo listFile : uploader.listFiles()) {
            if (listFile.getFilePath().equals(filePath) && listFile.getStatus().toString().equals(status)) {
                return listFile;
            }
        }
        return null;
    }

}
